﻿
using ChongJu.ModelManager.Config;
using ChongJu.ModelManager;
using ChongJu.ModelManager.Config;
using ChongJu.ModelManager.DeviceInfo;
using ChongJu.ModelManager.Farmer;
using ChongJu.ModelManager.Login;
using ChongJu.ModelManager.Rating;
using Public.Logger;
using Public.Tools;
using System;
using System.Collections.Generic;
using System.IO;

namespace ChongJu.GlobalInfo
{
    public static class GlobalVar
    {
        /// <summary>
        /// 当前运行模式 
        /// </summary>
        private static RunTypeEnum _currentRunType = 0;
        public static RunTypeEnum CurrentRunType
        {
            get { return _currentRunType; }
            set { _currentRunType = value; }
        }

        /// <summary>
        /// 设备信息-状态，一般用于大屏展示
        /// </summary>
        public static DeviceInfoModel DeviceInfo { get; set; }

        /// <summary>
        /// 分拣服务器连接状态
        /// </summary>
        public static bool LocalServiceConnected { get; set; }

        /// <summary>
        /// 因特网 网络延时
        /// </summary>
        public static long NetworkDelay { get; set; }

        /// <summary>
        /// 站点信息
        /// </summary>
        public static DeviceSiteModel SiteInfo { get; set; }

        /// <summary>
        /// 设备ID
        /// </summary>
        public static string DeviceID { get; set; } = Tool.GetMacAddress() + "_SIG";

        
        public static string AppVersion { get; } = Tool.GetAppVersion();

        /// <summary>
        /// 管理员用户
        /// </summary>
        public static UserModel User { get; set; } = new UserModel() { UserType = UserEnum.Operation };

        /// <summary>
        /// 设备状态信息
        /// </summary>
        public static DeviceInfoModel DeviceRatingStatus { get; set; } = new DeviceInfoModel();

        public static string LightType { get; set; }

        public static string DllVersion { get; set; }

        public static FileTransModel FileTransCfg
        {
            get
            {
                if (_fileTransCfg != null)
                    return _fileTransCfg;

                var file = Path.Combine(AppContext.BaseDirectory, "Config", "FileTrans.txt");
                var txt = Tool.Read(file);
                if (string.IsNullOrEmpty(txt) == true)
                {
                    _fileTransCfg = new FileTransModel();
                    Tool.Wirte(file, Tool.ObjectToJson(_fileTransCfg));
                }
                else
                {
                    _fileTransCfg = Tool.JsonToObject<FileTransModel>(txt);
                    if (_fileTransCfg.PerformanceInterval < 7.5)
                    {
                        _fileTransCfg.PerformanceInterval = 7.5;
                        Tool.Wirte(file, Tool.ObjectToJson(_fileTransCfg));
                    }
                }

                return _fileTransCfg;
            }
        }
        private static FileTransModel _fileTransCfg;


        /// <summary>
        /// 设置流程配置文件
        /// </summary>
        /// <param name="cfg"></param>
        public static void SetFileTransCfg(FileTransModel cfg)
        {
            _fileTransCfg = cfg;
        }


        #region 串口配置

        public static List<SerialPortModel> LstSerialPort
        {
            get
            {
                if (_lstSerialPort?.Count > 0)
                    return _lstSerialPort;

                if (File.Exists(ConfigFileInfo.SerialConfig) == false)
                    return null;

                var txt = Tool.Read(ConfigFileInfo.SerialConfig);
                _lstSerialPort = Tool.JsonToObject<List<SerialPortModel>>(txt);
                return _lstSerialPort;
            }
        }

        private static List<SerialPortModel> _lstSerialPort;


        #endregion


        #region 全局参数

        public static GlobalConfigModel GlobalParamer
        {
            get
            {
                return _globalParamer;
            }
        }

        public static void InitGlobalParamer()
        {
            if (_globalParamer != null)
                return;

            string txt = "";
            try
            {
                if (File.Exists(ConfigFileInfo.GlobalConfig) == false)
                {
                    Logger.Debug("全局配置文件不存在，开始自动生成配置");
                    _globalParamer = new GlobalConfigModel();
                    Tool.Wirte(ConfigFileInfo.GlobalConfig, Tool.ObjectToJson(_globalParamer));
                    return;
                }

                txt = Tool.Read(ConfigFileInfo.GlobalConfig).Trim('\0');
                if (string.IsNullOrWhiteSpace(txt) || txt.Trim().ToLower() == "null")
                {
                    Logger.Debug($"全局配置文件内容不合法:{txt}，开始自动生成配置");
                    _globalParamer = new GlobalConfigModel();
                    Tool.Wirte(ConfigFileInfo.GlobalConfig, Tool.ObjectToJson(_globalParamer));
                }
                else
                {
                    _globalParamer = Tool.JsonToObject<GlobalConfigModel>(txt);
                }
            }
            catch (Exception ex)
            {
                Logger.Error($"加载全局配置失败:{txt}", ex);
                _globalParamer = new GlobalConfigModel();
                Tool.Wirte(ConfigFileInfo.GlobalConfig, Tool.ObjectToJson(_globalParamer));
            }
            finally
            {
                if(_globalParamer == null)
                {
                    _globalParamer = new GlobalConfigModel();
                    Tool.Wirte(ConfigFileInfo.GlobalConfig, Tool.ObjectToJson(_globalParamer));
                }
            }
        }

        private static GlobalConfigModel _globalParamer;

        public static bool UpdateGlobalParamer(GlobalConfigModel cfg)
        {
            try
            {
                if (cfg == null)
                    return false;

                Logger.Debug($"UpdateGlobalParamer 配置文件 {ConfigFileInfo.GlobalConfig} \r\n {Tool.ObjectToJson(_globalParamer)}");
                var bol = Tool.Wirte(ConfigFileInfo.GlobalConfig, Tool.ObjectToJson(cfg));
                if (bol == false)
                    return false;

                _globalParamer = cfg;
                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        #endregion


        /// <summary>
        /// 分拣全局参数
        /// </summary>
        public static RatingConfigModel RatingConfig
        {
            get
            {
                if(_ratingConfig != null)
                    return _ratingConfig;

                if(File.Exists(ConfigFileInfo.RatingConfig) == false)
                {
                    _ratingConfig = new RatingConfigModel();
                    File.WriteAllText(ConfigFileInfo.RatingConfig, Tool.ObjectToJson(_ratingConfig));
                }
                else
                {
                    var txt = File.ReadAllText(ConfigFileInfo.RatingConfig);
                    _ratingConfig = Tool.JsonToObject<RatingConfigModel>(txt);
                }

                return _ratingConfig;
            }
        }

        private static RatingConfigModel _ratingConfig;

        public static bool UpdateRatingConfig(RatingConfigModel data)
        {
            try
            {
                _ratingConfig = data;
                File.WriteAllText(ConfigFileInfo.RatingConfig, Tool.ObjectToJson(data));
                return true;
            }
            catch(Exception ex)
            {
                return false;
            }
        }

        public static bool IsAdmin { get; set; } = false;
    }
}
